﻿using FluentScheduler;
using Glorysoft.Auto.Xfw;
using Glorysoft.EAP.Core;
using Glorysoft.EAP.Core.Entities;
using Glorysoft.EAP.Core.Enums;
using Glorysoft.EAP.RC.EAPClient;
using Serilog.Core;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace Glorysoft.EAP.EAPwell
{
    /// <summary>
    /// 监控monitor文件指定时间计划调度器
    /// </summary>
    public class CheckFileJob : IJob
    {
        private DbService dbServer = null;
        private readonly Logger CimLogger;
        public static DateTime CurrentTime;

        public CheckFileJob()
        {
            CimLogger = XfwContext.LogManager.DbLogger;
        }
        public void Execute()
        {

            dbServer = new DbService();
            DateTime nowTime = DateTime.Now;
            // 获取本周第一天 ,星期一为第一天  
            int weeknow = Convert.ToInt32(nowTime.DayOfWeek);
            //因为是以星期一为第一天，所以要判断weeknow等于0时，要向前推6天。  
            weeknow = (weeknow == 0 ? (7 - 1) : (weeknow - 1));
            int daydiff = (-1) * weeknow;
            DateTime FirstDay = nowTime.AddDays(daydiff).Date;//本周第一天  
            // 获取本周最后一天,//星期天为最后一天  
            int lastWeekDay = Convert.ToInt32(nowTime.DayOfWeek);
            lastWeekDay = lastWeekDay == 0 ? (7 - lastWeekDay) : lastWeekDay;
            int lastWeekDiff = (7 - lastWeekDay);
            DateTime LastDay = nowTime.AddDays(lastWeekDiff + 1).Date.AddSeconds(-1);//本周最后一天 
            var weekid = FirstDay.ToString("yyyyMMdd");
            var rptWeekid = dbServer.SeleteWeekid(weekid);
            if (rptWeekid == null)//不存在本周，新建一条原数据
            {
                dbServer.InsertMsgTo_Monitor_Time(0, DateTime.Now, weekid, DateTime.Now, "N");
            }
            else
            {
                //本周完成monitor,后续不执行
                if (rptWeekid.MONITORTEST == "Y")
                {
                    return;
                }
                else
                {
                    EAPClientService clientService = new EAPClientService();
                    string path = Dict.Current.MonitorTestDataPath;
                    bool Exists = Directory.Exists(path);
                    if (Exists == true)
                    {
                        DirectoryInfo root = new DirectoryInfo(path);
                        DirectoryInfo directory = root.GetDirectories().OrderBy(n => n.LastWriteTime).Last();
                        DirectoryInfo directoryInfo = new DirectoryInfo(directory.FullName);
                        FileInfo[] files = directoryInfo.GetFiles();
                        List<string> filelist = new List<string>();
                        List<string> file = new List<string>();
                        List<DateTime> timelist = new List<DateTime>();
                        foreach (FileInfo f in files)
                        {
                            string name = f.Name;
                            if (name.Contains(Dict.Current.TesterID))//Dict.Current.TesterID
                            {
                                string fullName = f.FullName;
                                DateTime filedt = f.LastWriteTime;//获取文件最后的写入时间
                                filelist.Add(name + ";" + filedt);
                            }
                        }
                        if (filelist.Count() == 0)//文件里是空，本周内设备未进行monitor测试
                        {
                            var Weekid = dbServer.SeleteWeekid(weekid);
                            if (rptWeekid != null)
                            {
                                int count = Convert.ToInt32(rptWeekid.COUNT) + 1;
                                dbServer.UpdateMsgTo_Monitor_Time(count, DateTime.Now, weekid, DateTime.Now, "N");
                            }
                            Dictionary<string, string> messagess = null;
                            var ClientMsg = "";
                            var messageType = MessageType.Info;
                            //本周内，此机台未跑monitor片，EAP进行报警
                            if (rptWeekid.COUNT == 1)//==3
                            {
                                var messages = TranslateMsg.GetTranslation("EAPMonitorRemindOne");
                                clientService.ShowMessage(Dict.Current.TesterID, MessageType.Alarm, messages, MessageOrigin.OCR);
                                ClientMsg = messages.ToString();
                                messagess = new Dictionary<string, string>();
                                messagess.Add("EN", ClientMsg);
                                messagess.Add("CN", ClientMsg);
                                messageType = MessageType.Alarm;
                                CimLogger.Information("本周内设备未进行monitor测试");
                                dbServer.InsertMsgInfo("本周内设备未进行monitor测试", Dict.Current.TesterID);
                                return;
                            }
                            //提醒次数超3/1次，不再进行处理
                            else if (rptWeekid.COUNT > 1)//3
                            {
                                return;
                            }
                            else
                            {
                                var messages = TranslateMsg.GetTranslation("EAPMonitorRemindOne");
                                clientService.ShowMessage(Dict.Current.TesterID, MessageType.Alarm, messages, MessageOrigin.OCR);
                                ClientMsg = messages.ToString();
                                messagess = new Dictionary<string, string>();
                                messagess.Add("EN", ClientMsg);
                                messagess.Add("CN", ClientMsg);
                                messageType = MessageType.Alarm;
                                CimLogger.Information("本周内设备未进行monitor测试");
                                dbServer.InsertMsgInfo("本周内设备未进行monitor测试", Dict.Current.TesterID);
                            }
                        }
                        else
                        {
                            for (int i = 0; i < filelist.Count; i++)//文件夹里有文件
                            {
                                var temptime = DateTime.Parse(filelist[i].Split(";")[1]);
                                var tempfile = filelist[i].Split(";")[0];
                                timelist.Add(temptime);
                                file.Add(tempfile);
                            }
                            timelist.Sort((x, y) => DateTime.Compare(x.Date, y.Date));
                            DateTime times = DateTime.Parse(timelist.Last().ToString());
                            var filename = file.Last().ToString();
                            if (times > FirstDay && times < LastDay)
                            {
                                //本周内，此机台有跑monitor片，EAP不进行报警                 
                                CurrentTime = times;
                                CimLogger.Information($"本周已进行monitor测试，文件名称:{filename}");
                                dbServer.InsertMsgInfo($"本周已进行monitor测试，文件名称:{filename}");
                                var dbWeekid = dbServer.SeleteWeekid(weekid);
                                if (dbWeekid != null)
                                {
                                    int count = Convert.ToInt32(dbWeekid.COUNT);
                                    dbServer.UpdateMsgTo_Monitor_Time(count, DateTime.Now, weekid, DateTime.Now, "Y");
                                }
                            }
                            else
                            {
                                var dbWeekid = dbServer.SeleteWeekid(weekid);
                                if (dbWeekid != null)
                                {
                                    int count = Convert.ToInt32(dbWeekid.COUNT) + 1;
                                    dbServer.UpdateMsgTo_Monitor_Time(count, DateTime.Now, weekid, DateTime.Now, "N");
                                }
                                Dictionary<string, string> messagess = null;
                                var ClientMsg = "";
                                var messageType = MessageType.Info;
                                //本周内，此机台未跑monitor片，EAP进行报警
                                if (rptWeekid.COUNT == 1)//==3
                                {
                                    var messages = TranslateMsg.GetTranslation("EAPMonitorRemindOne");
                                    clientService.ShowMessage(Dict.Current.TesterID, MessageType.Alarm, messages, MessageOrigin.OCR);
                                    ClientMsg = messages.ToString();
                                    messagess = new Dictionary<string, string>();
                                    messagess.Add("EN", ClientMsg);
                                    messagess.Add("CN", ClientMsg);
                                    messageType = MessageType.Alarm;
                                    CimLogger.Information("本周内设备未进行monitor测试");
                                    dbServer.InsertMsgInfo("本周内设备未进行monitor测试");
                                    return;
                                }
                                else if (rptWeekid.COUNT >1)
                                {
                                    //CimLogger.Information("本周内设备未进行monitor测试,提醒次数大于3次。使用EAP run货已锁机，不再进行提醒。");
                                    CimLogger.Information("本周内设备未进行monitor测试,提醒次数大于1次。使用EAP run货已锁机，不再进行提醒。");
                                    return;
                                }
                                else
                                {
                                    var messages = TranslateMsg.GetTranslation("EAPMonitorRemindOne");
                                    clientService.ShowMessage(Dict.Current.TesterID, MessageType.Alarm, messages, MessageOrigin.OCR);
                                    ClientMsg = messages.ToString();
                                    messagess = new Dictionary<string, string>();
                                    messagess.Add("EN", ClientMsg);
                                    messagess.Add("CN", ClientMsg);
                                    messageType = MessageType.Alarm;
                                    CimLogger.Information("本周内设备未进行monitor测试");
                                    dbServer.InsertMsgInfo("本周内设备未进行monitor测试");
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
